'use strict';

/* Directives */

angular.module('gmap', [])
	.directive('map', function(Places) {
	    return function (scope, element, attrs) {
	    	element.addClass('map');
			var map = new google.maps.Map(element[0], {
                zoom: 4,
                center: new google.maps.LatLng(45, 2),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: true
            });
            var gmarkers = [];
            scope.map = map;
            
            scope.$watch('places', function (newValue, oldValue) {
            	console.debug(newValue);
            	var i, marker;
            	for (i = 0; i < gmarkers.length; i ++) {
            		gmarkers[i].setMap(null);
            	}
            	gmarkers.length = 0;
            	if (newValue) {
	            	for (i = 0; i < newValue.length; i ++) {
	            		gmarkers.push(new google.maps.Marker({
					      	map: map,
					      	position: newValue[i].geometry.location,
                            title: newValue[i].name
					    }));
	            	}
        		}
            });

	    };	
	})
    .directive('search', function () {
        return function (scope, element, attrs) {

            var autocomplete = new google.maps.places.Autocomplete(element[0], {
              types: ['establishment']
            });
            
            scope.$watch('map', function (newValue, oldValue) {    
                console.info('Bind map');
                autocomplete.bindTo('bounds', newValue);
            });
            
            /*google.maps.event.addListener(autocomplete, 'places_changed', function() {
                console.info('places_changed');                
                scope.places = autocomplete.getPlaces();
                scope.$digest();
            });*/

            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                console.info('places_changed');                
                scope.places = [autocomplete.getPlace()];
                scope.$digest();
            });
            
             
        };  
    });